<?php

declare(strict_types=1);

namespace app\admin\service\settings;

use app\admin\job\NoticeJob;
use app\common\model\NoticeModel;
use app\common\model\user\UserModel;
use Dengje\Pxy\BaseService;
use dengje\workerman\process\queue\Client;

class NoticeService extends BaseService
{
    protected $model = null;


    public function __construct()
    {
        $this->model =  new \app\common\model\NoticeModel();
    }

    public function list()
    {
        $where = [];
        $title = request()->get('title');
        $content = request()->get('content');
        if ($title) $where[] = ['title', 'like', '%' . $title . '%'];
        if ($content) $where[] = ['content', 'like', '%' . $content . '%'];
        $list = $this->model->where($where)->order(['id' => 'desc', 'read' => 'asc'])->paginate(request()->get('page_size/d', 10));
        $list->map(function ($v) {
            if ($v['launch_id'] > 0) $v['launch'] = UserModel::where('id', $v['launch_id'])->field('name,avatar')->find();
            if (!$v['launch']) $v['launch'] = ['name' => '系统通知', 'avatar' => ''];
            if ($v['user_id'] > 0) $v['user'] = UserModel::where('id', $v['user_id'])->field('id,name,avatar')->find();
            if (!$v['user']) $v['user'] = ['name' => '异常通知', 'avatar' => ''];
            return $v;
        });
        return $list;
    }

    public function detail($id)
    {
        $detail = $this->model->where('id', $id)->find();
        return $detail;
    }

    public function create($data)
    {
        (new Client())->push(NoticeJob::class, $data);
        return;
    }

    public function update($id, $data)
    {
        $data = $this->preExcludeFields($data);
        return $this->model->where('id', $id)->update($data);
    }

    public function delete($id)
    {
        $this->model->where('id', $id)->delete();
        return success('删除成功！');
    }
}
